package com.biboheart.adapter.express.support;

import com.biboheart.adapter.express.actuator.GenericActuator;
import com.biboheart.adapter.support.utils.ObjectTypeUtils;

final class ReplaceActuator implements GenericActuator {
    static final String DELIM_STR = "{}";

    @Override
    public Object execute(Object source, Object... args) {
        if (null == source) {
            return null;
        }
        String messagePattern = String.valueOf(source);
        if (!messagePattern.contains(DELIM_STR)) {
            return source;
        }
        StringBuilder buff = new StringBuilder();
        int i = 0;
        int j;
        for (Object arg : args) {
            j = messagePattern.indexOf(DELIM_STR, i);
            if (j < 0) {
                buff.append(messagePattern, i, messagePattern.length());
                break;
            } else {
                buff.append(messagePattern, i, j).append(ObjectTypeUtils.convertType(arg, String.class));
                i = j + DELIM_STR.length();
            }
        }
        if (i < messagePattern.length()) {
            buff.append(messagePattern, i, messagePattern.length());
        }
        return buff.toString();
    }
}
